package cn.studyjams.s1.contest.autohello;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class AddTagFragment extends DialogFragment {

    private static final String REQUIRED = "Required";

    AddTagListener addTagListener;

    public interface AddTagListener {
        void onConfirmAddTag(String tag);

        void onCancelAddTag();
    }

    public AddTagFragment() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow()
                    .setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            addTagListener = (AddTagListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + "must implement AddTagFragment");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_add_tag, null);
        String tag = getArguments().getString("tag");

        final EditText tagET = (EditText) view.findViewById(R.id.tag);
        tagET.setText(tag);
        tagET.setSelection(tagET.getText().length());

        final AddTagListener addTagListener = (AddTagListener) getActivity();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);

        builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (tagET.getText().toString().equals("")) {
                    tagET.setError(REQUIRED);
                    return;
                }

                addTagListener.onConfirmAddTag(tagET.getText().toString());
                dismiss();
            }
        }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                addTagListener.onCancelAddTag();
                dismiss();
            }
        });

        return builder.create();
    }
}
